<?php

namespace App\Service\CallingCards;

use App\Models\FeishuCallingCard\FeishuCallingCardStory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

/**
 * 加盟商故事
 */
class StoryService
{
    public static function index($limit = null, $id = 0): array
    {
        return static::getStoryList($limit, $id);
    }

    public static function getStoryFromMp(int $count = 999)
    {
        $url  = 'https://mp.weixin.qq.com/mp/appmsgalbum?' . http_build_query([
                'action'        => 'getalbum',
                'album_id'      => '2129686410218536961',
                'count'         => $count,
                'uin'           => '',
                'key'           => '',
                'pass_ticket'   => '',
                'wxtoken'       => '',
                'devicetype'    => '',
                'clientversion' => '',
                '__biz'         => 'Mzg4ODA0MjczMA==',
                'enterid'       => '1637235562',
                'appmsg_token'  => '',
                'x5'            => '0',
                'f'             => 'json',
            ]);
        $data = Http::withHeaders([
            'Referer'    => 'https://mp.weixin.qq.com/mp/appmsgalbum?__biz=Mzg4ODA0MjczMA==&action=getalbum&album_id=2129686410218536961&scene=173&subscene=93&sessionid=0&enterid=1637235562&from_msgid=2247493121&from_itemidx=1&count=3&nolastread=1',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
        ])->get($url)->json();
        $list = $data['getalbum_resp']['article_list'] ?? [];

        $ids = [];
        foreach ($list as $k => $item) {
            $url = mb_substr($item['url'] ?? '', 0, 255);
            if (Str::startsWith($url, 'http://')) {
                $url = 'https://' . mb_substr($url, 7);
            }
            if (!strlen($url)) {
                continue;
            }
            $html = Http::withHeaders([
                'Referer'    => $url,
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
            ])->get($url)->body();
            //匹配出所有的字符串
            preg_match_all('/var msg_cdn_url = \"(.*?)\"/s', $html, $matches);
            $story = FeishuCallingCardStory::firstOrNew(['url' => $url]);
            $story->coverImg = mb_substr($item['cover_img_1_1'] ?? '', 0, 255);
            $story->coverBigImg = $matches[1][0] ?? '';
            $story->title = mb_substr($item['title'] ?? '', 0, 120);
            $story->status = FeishuCallingCardStory::DEFAULT_STATUS;// 显示
            $story->save();
            $ids[] = $story->id;
        }
        if (count($ids)) {
            FeishuCallingCardStory::query()
                ->whereNotIn('id', $ids)
                ->where('status', FeishuCallingCardStory::DEFAULT_STATUS)// 显示
                ->update(['status' => FeishuCallingCardStory::DELETE_STATUS]);// 隐藏
        }
    }

    public static function getStoryList($limit, int $id = 0): array
    {
        return FeishuCallingCardStory::query()
            ->when(
                $id, function ($query) use ($id) {
                $query->where('id', $id);
            }
            )
            ->where('status', FeishuCallingCardStory::DEFAULT_STATUS)// 显示
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->get()
            ->map(function (FeishuCallingCardStory $feishuCallingCardStory) {
                return [
                    'id'          => $feishuCallingCardStory->id,
                    'coverImg'    => $feishuCallingCardStory->coverImg,
                    'coverBigImg' => $feishuCallingCardStory->coverBigImg,
                    'url'         => $feishuCallingCardStory->url,
                    'title'       => $feishuCallingCardStory->title,
                    'create_time' => $feishuCallingCardStory->createdAt->timestamp,
                ];
            })->values()->toArray();
    }
}
